Imports System.Drawing

Imports ExpertPdf.HtmlToPdf
Imports ExpertPdf.HtmlToPdf.PdfDocument

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvert.Click
        Dim pdfConverter As PdfConverter = New PdfConverter()

        ' inform the converter about the HTML elements for which we want the location in PDF
        ' in this sample we want the location of IMG, H1 and H2 elements
        pdfConverter.HtmlElementsMappingOptions.HtmlTagNames = New String() {"IMG", "H1", "H2"}
        ' add an addtional list of the HTML IDs of the HTML elements for which to retrieve position in PDF
        pdfConverter.HtmlElementsMappingOptions.HtmlElementIds = New String() {"id1", "id2"}

        ' call the converter and get a Document object from URL
        Dim pdfDocument As Document = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL.Text.Trim())

        ' iterate over the HTML elements locations and hightlight each element with a green rectangle
        For Each elementMapping As HtmlElementMapping In pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult

            ' because a HTML element can span over many PDF pages the mapping 
            ' of the HTML element in PDF document consists in a list of rectangles,
            ' one rectangle for each PDF page where this element was rendered
            For Each elementLocationInPdf As HtmlElementPdfRectangle In elementMapping.PdfRectangles

                ' get the PDF page
                Dim pdfPage As PdfPage = pdfDocument.Pages.Item(elementLocationInPdf.PageIndex)
                Dim pdfRectangleInPage As RectangleF = elementLocationInPdf.Rectangle

                ' create a RectangleElement to highlight the HTML element
                Dim highlightRectangle As RectangleElement = New RectangleElement(pdfRectangleInPage.X, pdfRectangleInPage.Y, pdfRectangleInPage.Width, pdfRectangleInPage.Height)
                highlightRectangle.ForeColor = Color.Green

                pdfPage.AddElement(highlightRectangle)
            Next
        Next

        ' call the converter
        Dim pdfBytes As Byte()

        Try
            pdfBytes = pdfDocument.Save()
        Finally
            ' close the Document to realease all the resources
            pdfDocument.Close()
        End Try

        ' send the PDF document as a response to the browser for download
        Dim Response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        Response.Clear()
        Response.AddHeader("Content-Type", "binary/octet-stream")
        Response.AddHeader("Content-Disposition", "attachment; filename=ConversionResult.pdf; size=" & pdfBytes.Length.ToString())
        Response.Flush()
        Response.BinaryWrite(pdfBytes)
        Response.Flush()
        Response.End()

    End Sub

End Class
